package com.cloudmusic.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cloudmusic.service.ImgeService;

@Controller
@RequestMapping("music/imge")
public class ImgeShowController {

	@Autowired
	ImgeService imgeService;
	
	private Logger log=Logger.getLogger(this.getClass());

	@RequestMapping("show")
	public void imgeShow(HttpServletRequest request,HttpServletResponse respons,String songId) {
		File file = null;
		if (songId == null) {
			String path = request.getSession().getServletContext().getRealPath("/img/bgimg/moren.jpg");
			file = new File(path);
			fileResponsfuntion(respons, file);
		} else {
			String imgSrc = imgeService.imgeShow(songId);
			if (imgSrc == null) {
				String path = request.getSession().getServletContext().getRealPath("/img/bgimg/moren.jpg");
				file = new File(path);
				fileResponsfuntion(respons, file);

			} else {
				file = new File(imgSrc);
				fileResponsfuntion(respons, file);
			}
		}

	}

	public void fileResponsfuntion(HttpServletResponse response, File file) {
		OutputStream out = null;
		try {
			InputStream inputStream = new FileInputStream(file);
			out = response.getOutputStream();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("image/jpg");
			byte[] buff = new byte[1024 * 4];
			int index = 0;
			while ((index = inputStream.read(buff)) != -1) {
				out.write(buff, 0, index);
			}
			out.flush();
			log.info("读取图片成功");
		} catch (Exception e) {
			log.error("读取图片有异常",e);
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				log.error("关闭流失败",e);
			}
		}
	}

}
